import { defineStore } from "pinia";
import Layout from "@/layout/index.vue";
import dataMenus from "../dataMenus.js";

import router, { constantRoutes, dynamicRoutes } from "@/router/index.js";

const usePermissionStore = defineStore("permission", {
  state: () => ({
    sidebarRouters: [],
  }),
  getters: {
    getSidebarRouters: (state) => state.sidebarRouters,
  },

  actions: {
    setSidebarRouters(routers) {
      console.log("sidebarRoutes", routers);

      this.sidebarRouters = routers;
    },
    generateRoutes(roles) {
      return new Promise((resolve) => {
        const sdata = JSON.parse(JSON.stringify(dataMenus));
        const rdata = JSON.parse(JSON.stringify(dataMenus));

        const sidebarRoutes = filterAsyncRouter(sdata);
        const rewriteRoutes = filterAsyncRouter(rdata, false, true);

        this.setSidebarRouters(constantRoutes.concat(sidebarRoutes));
        // this.setSidebarRouters(constantRoutes);
        
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
        console.log('asyncRoutes',asyncRoutes)
        // asyncRoutes.forEach((route) => {
        //   router.addRoute(route);
        // });

        resolve(rewriteRoutes);
      });
    },
  },
});

export const modules = import.meta.glob("@/views/**/*.vue");
// console.log("modules", modules);
export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  // console.log(view,res);
  return res;
};
// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}
function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el));
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (route.meta) {
      const zh = route.meta.title;
      const en = route.meta.titleEn || route.meta.title;
      route.meta.locale_i18n = { en, zh };
    }
    // console.log(route.component,route)
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // console.log(route.component);

      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        /* else if (route.component === "ParentView") {
        route.component = ParentView;
      } else if (route.component === "InnerLink") {
        route.component = InnerLink; 
      } */
        route.component = loadView(route.component);
      }
      // debugger
      // console.log(route.component, route.name);
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

export default usePermissionStore;
